﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;
using System.Text;

namespace Justin.Service
{
    /// <summary>
    /// 对外是不可见的
    /// </summary>
     class ServiceSingletonProviderImpl : IServiceProvider
     {
        /// 服务缓存
        /// </summary>
        private Dictionary<Type, object> serviceCache = new Dictionary<Type, object>();


        /// <summary>
        /// 获取或创建服务
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public object GetService(Type serviceType) {
            object obj;
            if (!serviceCache.TryGetValue(serviceType, out obj)) {
                //反射接口
                var attrs = serviceType.GetCustomAttributes(typeof(ServiceAttribute), false);
                if (attrs.Length == 1) {
                    lock (serviceCache) {
                        //再次检查是否创建好了服务
                        if (!serviceCache.TryGetValue(serviceType, out obj)) {
                            var attr = (ServiceAttribute)attrs[0];
                            if (attr.ImplType != null) {
                                obj = Activator.CreateInstance(attr.ImplType);
                            }
                            else {
                                //请求查询插件树如果存在其实现服务就可以进行创建工作
                            }
                        }
                        serviceCache.Add(serviceType, obj);
                    }
                }
            }
            return obj;
        }
    }
}
